package database;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("entries")
public class EntryController {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private EntryRepository entries;

    @Autowired
    private EntryService es;

    @RequestMapping("test")
     public String test() {
        log.info("Test");
        return "OK";
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Entry getEntry(@PathVariable("id") long id) {
        log.info("Get entry :" + id);
        Entry n = entries.findOne(id);
        log.info(n.toString());
        boolean has = es.hasComments(id);
        log.info("Entry " + id + " hasComments:" + has);
        return n;
    }


    @RequestMapping("")
    @ResponseBody
    public List<Entry> getEntries() {
        log.info("Get entries");
        return entries.findAll();
    }


    @RequestMapping(value= "addEntry", method = RequestMethod.POST)
    public void addEntry(@RequestBody Entry entry) {
        log.info("Add entry");
        entries.save(entry);
    }

    @RequestMapping(value= "/{id}/updateEntry", method = RequestMethod.PUT)
    public void updateEntry(@RequestBody Entry entry) {
        String str = entry.getTitle() + entry.getBody();
        log.info(str);
        log.info("Updating entry:");
        entries.save(entry);
    }


    @RequestMapping(value="/{id}", method = RequestMethod.DELETE)
    public void deleteEntry(@PathVariable("id") long id) {
        log.info("Deleting entry :" + id);
        entries.delete(id);
    }


    @RequestMapping(value="/comments/{id}",method = RequestMethod.GET)
    public boolean comment(@PathVariable("id") long id) {
        boolean has = es.hasComments(id);
        log.info("Entry " + id + " hasComments:" + has);
        return has;
    }


    // To finish

   /* @RequestMapping("aze")
    public List<Entry> getEntries(@RequestParam("number") long number) {
        log.info("Get "+number+" last entries");
        List<Entry> le = entries.findAll();
        List<Entry> result = new ArrayList<Entry>();
        int i = 0;
        while(i<=number) {
            ;
            i++;
        }



        return result;
    }
*/

    /*public long getMax(ArrayList<Entry> list){
        long max = Integer.MIN_VALUE;
        for(int i=0; i<list.size(); i++){
            if(list.get(i).id > max){
                max = list.get(i).id;
            }
        }
        return max;
    }*/


}
